<template>
  <div class="wrap wrap_coupon_detail">
    <div class="coupon_detail">
      <div class="title">
        <img src="/static/img/lingxing.png" alt="" class="dot" />
        &yen;{{info.face_value}}
        <img src="/static/img/lingxing.png" alt="" class="dot" />
      </div>
      <div class="desc">{{info.name}}</div>
      <div class="sub_desc">有效期：至{{info.end_time}}</div>
      <a class="btn_em" @click="goListTab" v-if="info._isActive">立即使用</a>
      <a class="btn_em disabled" v-else>已过期</a>
      <div class="gap_line"></div>
      <div class="coupon_info">
        <div class="info_title">使用规则</div>
        <div class="info_desc">
          {{info.description}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import fly from '@/utils/fly'
import { getOpenid } from '@/utils/login'
import { formatTime } from '@/utils/index'
import { reportData } from '@/utils/report'

export default {
  data () {
    return {
      listData: [],
      hasNext: true,
      canLoadMore: true,
      info: {
        face_value: 0,
        name: '',
        description: '',
        end_time: ''
      }
    }
  },
  computed: {},
  methods: {
    async getList () {
      this.canLoadMore = false
      let openid = await getOpenid()
      let {
        codeId
      } = this.$root.$mp.query

      let url = `Coupon/details?wx_openid=${openid}&code_id=${codeId}`
      let res = await fly.post(url)
      if (res && res.code === 200 && res.data) {
        let info = res.data
        this.info.end_time = formatTime(new Date(info.end_time * 1000))
        this.info.name = info.name
        this.info.description = info.description
        this.info.face_value = info.face_value
        this.info.coupon_id = info.coupon_id

        info._isActiveTime = info.end_time >= (+new Date() / 1000)
        this.info._isActive = info._isActiveTime && info.is_used !== 1
      } else {
        wx.showToast({
          title: `数据异常${res ? ('(' + res.code + ')') : ''}`,
          icon: 'none'
        })
      }
      this.canLoadMore = true
    },
    goListTab () {
      try {
        wx.setStorageSync('couponDetail', '1')
      } catch (e) {
      }
      wx.switchTab({
        url: '/pages/goods-list/main?type=hot'
      })
    }
  },
  async onLoad () {
    wx.showLoading({
      title: '加载中'
    })
    await this.getList()
    wx.hideLoading()

    wx.setNavigationBarTitle({
      title: '优惠券'
    })

    reportData({
      funcx: '我的-我的优惠券详情',
      keyx: this.info.coupon_id
    })
  },
  onPullDownRefresh () {},
  onReachBottom () {
    if (this.hasNext && this.canLoadMore) {
      this.getList()
    }
  }
}
</script>

<style lang="scss">
  @import './coupon-detail.scss';
</style>
